
local cjson = require("cjson")
local http = require("resty.http")
local http = require("resty.redis")

local uri_args = ngx.req.get_uri_args()
local productId = uri_args["productId"]

local cache_ngx = ngx.shared.my_cache
local productCacheKey = "product_detail_"..productId
local productCache = cache_ngx:get(productCacheKey)

if productCache == "" or productCache == nil then
		local redis = redis:new()
		red:set_timeout(3000)
		local ip = "192.168.0.102"
		local port = 1111
		local ok, err = red:connect(ip, port)
		if not ok then
			ngx.say("connecto to redis error:", err)
			return close_redis(redis)
		end
		
		local redisResp, redisErr = red:get("dim_product_"..productId)
		
		if redisResp == ngx.null then
			local httpc = http.new()

			local resp, err = httpc:request_uri("http://192.168.0.100:8762",{
					method = "GET",
					path = "/product/selectOne?id="..productId,
					keepalive=false
			})
			productCache = resp.body
			cache_ngx:set(productCacheKey, productCache, 10*60)
		else
			productCache = redisResp
		end
end

local productCacheJSON = cjson.decode(productCache)

local context = {
	  product = productCacheJSON
}

local template = require("resty.template")
template.render("product.html", context)
